package com.atguigu.gmall.auth.service.impl;

import com.atguigu.core.bean.Resp;
import com.atguigu.core.utils.JwtUtils;
import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.fegin.GmallUmsClient;
import com.atguigu.gmall.auth.service.AuthService;
import com.atguigu.gmall.ums.entity.MemberEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@EnableConfigurationProperties(JwtProperties.class) //引入配置类
public class AuthServiceImpl implements AuthService {

    @Autowired
    private GmallUmsClient gmallUmsClient;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录授权
     * @param username
     * @param password
     */
    @Override
    public String authentication(String username, String password) {

        try {
            //1、远程校验用户名和密码
            Resp<MemberEntity> memberEntityResp = this.gmallUmsClient.queryUser(username, password);
            MemberEntity memberEntity = memberEntityResp.getData();
            //2\判断返回是否为空，如果为空则是，则代表失败
            // 如果查询结果为null，则直接返回null
            if (memberEntity == null) {
                return null;
            }
            //制作jwt,放入cookie
            Map<String,Object> map=new HashMap<>();
            map.put("id",memberEntity.getId());//用户id
            map.put("username",memberEntity.getUsername());
            //获取的是私钥
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire());//第二个放私钥对象
            return token;
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
}
